package com.itheima.reggie.controller;


import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.service.ShoppingCartService;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("shoppingCart")
public class ShoppingCartController {

    @Autowired
    private ShoppingCartService shoppingCartService;

    /**
     * 添加购物车功能
     * @param shoppingCart
     * @return
     */
    @PostMapping("add")
    public R<ShoppingCart> add(@RequestBody ShoppingCart shoppingCart, HttpSession session){
        //获取登录用户信息
        Long userId = (Long) session.getAttribute("user");
        shoppingCart.setUserId(userId);
        ShoppingCart newShoppingCart = shoppingCartService.add(shoppingCart);
        return R.success(newShoppingCart);
    }

    /**
     * 添加购物车功能
     * @param shoppingCart
     * @return
     */
    @PostMapping("sub")
    public R<ShoppingCart> decreaseNumber(@RequestBody ShoppingCart shoppingCart, HttpSession session){
        //获取登录用户信息
        Long userId = (Long) session.getAttribute("user");
        shoppingCart.setUserId(userId);
        ShoppingCart newShoppingCart = shoppingCartService.decreaseNumber(shoppingCart);
        return R.success(newShoppingCart);
    }

    /**
     * 查询购物车
     * @param session
     * @return
     */
    @GetMapping("list")
    public R<List<ShoppingCart>> list(HttpSession session){
        Long userId = (Long) session.getAttribute("user");
        List<ShoppingCart> shoppingCartList = shoppingCartService.findShoppingCartListByUserId(userId);
        return R.success(shoppingCartList);
    }

    /**
     * 清空购物车
     * @param session
     * @return
     */
    @DeleteMapping("/clean")
    public R<String> clean(HttpSession session){
        Long userId = (Long) session.getAttribute("user");
        shoppingCartService.delete(userId);
        return R.success("");

    }
}
